package com.atguigu.srb.sms.service.impl;

import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.util.RandomUtils;
import com.atguigu.srb.sms.service.SmsService;
import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author zwj
 * @create 2021-10-11 23:22
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void send(String mobile) {

        String code = RandomUtils.getFourBitRandom();

        //生产环境请求地址：app.cloopen.com
        String serverIp = "app.cloopen.com";
        //请求端口
        String serverPort = "8883";
        //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
        String accountSId = "8aaf07087c6ec45b017c6fd0c81d0092";
        String accountToken = "043695b8c51d4fb4bb0e014097d9ff82";
        //请使用管理控制台中已创建应用的APPID
        String appId = "8aaf07087c6ec45b017c6fd0c95a0099";
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        String to = mobile;
        String templateId = "1";
        String timeOut = "5";
        String[] datas = {code, timeOut};
        redisTemplate.opsForValue().set("srb:sms:code:" + mobile, code, Long.parseLong(timeOut), TimeUnit.MINUTES);
//        HashMap<String, Object> result = sdk.sendTemplateSMS(to, templateId, datas);
//        if ("000000".equals(result.get("statusCode"))) {
//            log.info("短信发送成功");
//            //正常返回输出data包体信息（map）
//            HashMap<String, Object> data = (HashMap<String, Object>) result.get("data");
//            Set<String> keySet = data.keySet();
//            for (String key : keySet) {
//                Object object = data.get(key);
//                log.info(key + " = " + object);
//            }
//
//            log.info("将验证码{}存入redis",code);
//            redisTemplate.opsForValue().set("srb:sms:code:" + mobile, code, Long.parseLong(timeOut), TimeUnit.MINUTES);
//
//        } else {
//            //异常返回输出错误码和错误信息
//            log.error("容联云短信服务发送失败");
//            log.error("错误码=" + result.get("statusCode") + " 错误信息= " + result.get("statusMsg"));
//            Integer statusCode = Integer.valueOf((String) result.get("statusCode"));
//            String message = (String) result.get("statusMsg");
//            throw new BusinessException(message, statusCode);
//        }

    }
}
